import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/constants.dart';
import '../../shared/models/coin_product.dart';
import '../../shared/providers/coin_provider.dart';
import '../../shared/services/coin_purchase_service.dart';

class CoinShopPage extends ConsumerStatefulWidget {
  const CoinShopPage({super.key});

  @override
  ConsumerState<CoinShopPage> createState() => _CoinShopPageState();
}

class _CoinShopPageState extends ConsumerState<CoinShopPage>
    with TickerProviderStateMixin {
  late TabController _tabController;
  final Set<String> _loadingProducts = <String>{};
  final CoinPurchaseService _purchaseService = CoinPurchaseService();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _initializePurchaseService();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _initializePurchaseService() async {
    try {
      await _purchaseService.initialize();
      
      // 设置购买状态回调
      _purchaseService.onPurchaseStateChanged = (productId, isLoading, error) {
        if (mounted) {
          setState(() {
            if (isLoading) {
              _loadingProducts.add(productId);
            } else {
              _loadingProducts.remove(productId);
            }
          });


        }
      };
      
      // 设置金币添加回调
      _purchaseService.onCoinsAdded = (coins) {
        if (mounted) {
          ref.read(coinBalanceProvider.notifier).refreshBalance();
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Row(
                children: [
                  const FaIcon(FontAwesomeIcons.circleCheck, color: Colors.white, size: 20),
                  const SizedBox(width: 12),
                  Text('Purchase successful! +$coins coins'),
                ],
              ),
              backgroundColor: AppConstants.PRIMARY_BLUE,
              behavior: SnackBarBehavior.floating,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            ),
          );
        }
      };
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Failed to initialize purchase service: $e'),
            backgroundColor: Colors.red,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
        );
      }
    }
  }

  Future<void> _purchaseProduct(CoinProduct product) async {
    if (_loadingProducts.contains(product.productId)) return;
    
    try {
      await _purchaseService.purchaseProduct(product);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Error: ${e.toString()}'),
            backgroundColor: Colors.red,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
        );
      }
    }
  }

  Widget _buildProductCard(CoinProduct product) {
    final bool isLoading = _loadingProducts.contains(product.productId);
    
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 顶部图标和促销标识
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: product.isPromo 
                        ? Colors.orange.withOpacity(0.1)
                        : AppConstants.PRIMARY_BLUE.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: FaIcon(
                    FontAwesomeIcons.coins,
                    color: product.isPromo ? Colors.orange : AppConstants.PRIMARY_BLUE,
                    size: 20,
                  ),
                ),
                const Spacer(),
                if (product.isPromo)
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.orange,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Text(
                      'PROMO',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                        fontWeight: FontWeight.bold,
                        letterSpacing: 0.5,
                      ),
                    ),
                  ),
              ],
            ),
            const SizedBox(height: 16),
            
            // 金币数量
            Text(
              '${product.coins}',
              style: TextStyle(
                fontSize: 32,
                fontWeight: FontWeight.bold,
                color: product.isPromo ? Colors.orange : AppConstants.PRIMARY_BLUE,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              'COINS',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w600,
                color: Colors.grey[600],
                letterSpacing: 1.0,
              ),
            ),
            
            const SizedBox(height: 8),

            // 购买按钮
            SizedBox(
              width: double.infinity,
              height: 48,
              child: ElevatedButton(
                onPressed: isLoading ? null : () => _purchaseProduct(product),
                style: ElevatedButton.styleFrom(
                  backgroundColor: product.isPromo ? Colors.orange : AppConstants.PRIMARY_BLUE,
                  foregroundColor: Colors.white,
                  elevation: 0,
                  shadowColor: Colors.transparent,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: EdgeInsets.zero,
                ),
                child: isLoading
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                          strokeWidth: 2,
                        ),
                      )
                    : Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const FaIcon(
                            FontAwesomeIcons.creditCard,
                            size: 16,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            '\$${product.price.toStringAsFixed(2)}',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCoinsTab() {
    final products = CoinProduct.allProducts;
    
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          GridView.builder(
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 16,
              mainAxisSpacing: 16,
              childAspectRatio: 0.75,
            ),
            itemCount: products.length,
            itemBuilder: (context, index) {
              return _buildProductCard(products[index]);
            },
          ),
          const SizedBox(height: 40),
        ],
      ),
    );
  }

  Widget _buildVipTab() {
    final vipPlans = VipPlan.getAllPlans;
    final coinBalance = ref.watch(coinBalanceProvider);
    final vipStatus = ref.watch(vipStatusProvider);
    
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // VIP介绍卡片
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  AppConstants.PRIMARY_BLUE,
                  AppConstants.DARK_BLUE,
                ],
              ),
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: AppConstants.PRIMARY_BLUE.withOpacity(0.3),
                  spreadRadius: 1,
                  blurRadius: 10,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const FaIcon(
                    FontAwesomeIcons.crown,
                    color: Colors.white,
                    size: 28,
                  ),
                ),
                const SizedBox(height: 16),
                const Text(
                  'VIP Premium',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 8),
                if (vipStatus.isVip) ...[
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Text(
                      vipStatus.remainingDays == -1 
                          ? 'Lifetime VIP Active'
                          : '${vipStatus.remainingDays} days remaining',
                      style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  const Text(
                    'Extend your VIP subscription below',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.white70,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ] else ...[
                  const Text(
                    'Unlock unlimited daily quizzes and premium features',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.white70,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ],
              ],
            ),
          ),
          
          const SizedBox(height: 24),
          
          // VIP计划列表
          ...vipPlans.map((plan) => _buildVipPlanCard(plan, coinBalance)).toList(),
          
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  Widget _buildVipPlanCard(VipPlan plan, int coinBalance) {
    final bool canAfford = coinBalance >= plan.coinsCost;
    final bool isLoading = _loadingProducts.contains(plan.planId);
    final vipStatus = ref.watch(vipStatusProvider);
    final bool isLifetimeVip = vipStatus.isVip && vipStatus.remainingDays == -1;
    final bool shouldDisable = isLifetimeVip && plan.planId != 'vip_lifetime';
    
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: plan.isPopular 
            ? Border.all(color: AppConstants.PRIMARY_BLUE, width: 2)
            : null,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Stack(
        children: [
          // 徽章
          if (plan.badge.isNotEmpty)
            Positioned(
              top: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: plan.isPopular 
                      ? AppConstants.PRIMARY_BLUE 
                      : plan.badge == 'LIFETIME' 
                          ? Colors.purple 
                          : Colors.orange,
                  borderRadius: const BorderRadius.only(
                    topRight: Radius.circular(16),
                    bottomLeft: Radius.circular(12),
                  ),
                ),
                child: Text(
                  plan.badge,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 10,
                    fontWeight: FontWeight.bold,
                    letterSpacing: 0.5,
                  ),
                ),
              ),
            ),
          
          // 终身VIP用户不可购买其他套餐的覆盖层
          if (shouldDisable)
            Positioned.fill(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey.withOpacity(0.3),
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
            ),
          
          Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 计划名称和时长
                Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            plan.name,
                            style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                              color: shouldDisable 
                                  ? Colors.grey 
                                  : AppConstants.PRIMARY_BLUE,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            plan.description,
                            style: TextStyle(
                              fontSize: 14,
                              color: shouldDisable 
                                  ? Colors.grey 
                                  : Colors.grey[600],
                            ),
                          ),
                        ],
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Row(
                          children: [
                            FaIcon(
                              FontAwesomeIcons.coins,
                              color: shouldDisable ? Colors.grey : Colors.orange,
                              size: 16,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              '${plan.coinsCost}',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                                color: shouldDisable ? Colors.grey : Colors.orange,
                              ),
                            ),
                          ],
                        ),
                        if (plan.durationDays > 0)
                          Text(
                            '${(plan.coinsCost / plan.durationDays).toStringAsFixed(1)} coins/day',
                            style: TextStyle(
                              fontSize: 12,
                              color: shouldDisable 
                                  ? Colors.grey 
                                  : Colors.grey[500],
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
                
                const SizedBox(height: 16),
                
                // 主要功能
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: shouldDisable 
                        ? Colors.grey.withOpacity(0.1)
                        : AppConstants.PRIMARY_BLUE.withOpacity(0.05),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    children: [
                      FaIcon(
                        FontAwesomeIcons.infinity,
                        size: 16,
                        color: shouldDisable 
                            ? Colors.grey 
                            : AppConstants.PRIMARY_BLUE,
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Text(
                          'Unlimited Daily Quizzes',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: shouldDisable 
                                ? Colors.grey 
                                : const Color(0xFF1C1C1E),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                
                const SizedBox(height: 16),

                // 终身VIP提示信息
                if (shouldDisable)
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.amber.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: Colors.amber.withOpacity(0.3),
                        width: 1,
                      ),
                    ),
                    child: Row(
                      children: [
                        const FaIcon(
                          FontAwesomeIcons.crown,
                          size: 16,
                          color: Colors.amber,
                        ),
                        const SizedBox(width: 12),
                        const Expanded(
                          child: Text(
                            'You already have Lifetime VIP access',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: Colors.amber,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                
                if (shouldDisable) const SizedBox(height: 16),
                
                // 购买按钮
                SizedBox(
                  width: double.infinity,
                  height: 48,
                  child: ElevatedButton(
                    onPressed: (isLoading || !canAfford || shouldDisable) 
                        ? null 
                        : () => _purchaseVipPlan(plan),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: shouldDisable 
                          ? Colors.grey[300]
                          : plan.isPopular 
                              ? AppConstants.PRIMARY_BLUE 
                              : AppConstants.DARK_BLUE,
                      foregroundColor: shouldDisable 
                          ? Colors.grey[600]
                          : Colors.white,
                      elevation: 0,
                      shadowColor: Colors.transparent,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      padding: EdgeInsets.zero,
                    ),
                    child: isLoading
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                              strokeWidth: 2,
                            ),
                          )
                        : Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              if (shouldDisable) ...[
                                const FaIcon(
                                  FontAwesomeIcons.crown,
                                  size: 16,
                                ),
                                const SizedBox(width: 8),
                                const Text(
                                  'Already Owned',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ] else if (!canAfford) ...[
                                const FaIcon(
                                  FontAwesomeIcons.lock,
                                  size: 16,
                                ),
                                const SizedBox(width: 8),
                                const Text(
                                  'Insufficient Coins',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ] else ...[
                                const FaIcon(
                                  FontAwesomeIcons.crown,
                                  size: 16,
                                ),
                                const SizedBox(width: 8),
                                Text(
                                  'Activate ${plan.displayDuration}',
                                  style: const TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ],
                          ),
                  ),
                ),
                
              ],
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _purchaseVipPlan(VipPlan plan) async {
    if (_loadingProducts.contains(plan.planId)) return;
    
    // 显示确认对话框
    final confirmed = await _showVipPurchaseConfirmation(plan);
    if (!confirmed) return;
    
    setState(() {
      _loadingProducts.add(plan.planId);
    });
    
    try {
      // 模拟购买过程
      await Future.delayed(const Duration(seconds: 2));
      
      // 扣除金币
      final currentBalance = ref.read(coinBalanceProvider);
      if (currentBalance >= plan.coinsCost) {
        await ref.read(coinBalanceProvider.notifier).spendCoins(plan.coinsCost);
        
        // 激活VIP
        if (plan.durationDays == -1) {
          await ref.read(vipStatusProvider.notifier).activateLifetimeVip();
        } else {
          await ref.read(vipStatusProvider.notifier).activateVip(plan.durationDays);
        }
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Row(
                children: [
                  const FaIcon(FontAwesomeIcons.crown, color: Colors.white, size: 20),
                  const SizedBox(width: 12),
                  Text('VIP ${plan.displayDuration} activated successfully!'),
                ],
              ),
              backgroundColor: AppConstants.PRIMARY_BLUE,
              behavior: SnackBarBehavior.floating,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            ),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Failed to activate VIP: ${e.toString()}'),
            backgroundColor: Colors.red,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _loadingProducts.remove(plan.planId);
        });
      }
    }
  }

  Future<bool> _showVipPurchaseConfirmation(VipPlan plan) async {
    return await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: AppConstants.PRIMARY_BLUE.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: FaIcon(
                FontAwesomeIcons.crown,
                color: AppConstants.PRIMARY_BLUE,
                size: 20,
              ),
            ),
            const SizedBox(width: 12),
            const Text('Confirm VIP Purchase'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'You are about to purchase:',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: AppConstants.PRIMARY_BLUE.withOpacity(0.05),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    plan.name,
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: AppConstants.PRIMARY_BLUE,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    plan.description,
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 12),
                  Row(
                    children: [
                      const FaIcon(
                        FontAwesomeIcons.infinity,
                        size: 14,
                        color: Colors.green,
                      ),
                      const SizedBox(width: 8),
                      const Text(
                        'Unlimited Daily Quizzes',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        'Cost:',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      Row(
                        children: [
                          const FaIcon(
                            FontAwesomeIcons.coins,
                            color: Colors.orange,
                            size: 14,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            '${plan.coinsCost}',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.orange,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            Text(
              plan.durationDays == -1 
                  ? 'This will give you lifetime VIP access.'
                  : 'VIP time will be added to your current subscription.',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[500],
                fontStyle: FontStyle.italic,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: Text(
              'Cancel',
              style: TextStyle(color: Colors.grey[600]),
            ),
          ),
          ElevatedButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppConstants.PRIMARY_BLUE,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: const Text('Confirm Purchase'),
          ),
        ],
      ),
    ) ?? false;
  }

  @override
  Widget build(BuildContext context) {
    final coinBalance = ref.watch(coinBalanceProvider);
    
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            expandedHeight: 140,
            floating: true,
            pinned: true,
            snap: false,
            elevation: 0,
            backgroundColor: Colors.transparent,
            leading: IconButton(
              icon: const FaIcon(FontAwesomeIcons.arrowLeft, color: Colors.white, size: 20),
              onPressed: () => Navigator.of(context).pop(),
            ),
            flexibleSpace: FlexibleSpaceBar(
              background: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      AppConstants.PRIMARY_BLUE,
                      AppConstants.PRIMARY_BLUE.withOpacity(0.8),
                      AppConstants.DARK_BLUE,
                    ],
                  ),
                ),
                child: SafeArea(
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(24, 20, 24, 20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.all(8),
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.2),
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: const FaIcon(
                                FontAwesomeIcons.store,
                                color: Colors.white,
                                size: 24,
                              ),
                            ),
                            const SizedBox(width: 12),
                            const Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    'Coin Shop',
                                    style: TextStyle(
                                      fontSize: 28,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.white,
                                      letterSpacing: 1.2,
                                    ),
                                  ),
                           
                                ],
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.2),
                                borderRadius: BorderRadius.circular(20),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  const FaIcon(
                                    FontAwesomeIcons.coins,
                                    color: Colors.white,
                                    size: 16,
                                  ),
                                  const SizedBox(width: 8),
                                  Text(
                                    '$coinBalance',
                                    style: const TextStyle(
                                      color: Colors.white,
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 20),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            bottom: PreferredSize(
              preferredSize: const Size.fromHeight(0),
              child: Container(
                height: 20,
                decoration: BoxDecoration(
                  color: Theme.of(context).scaffoldBackgroundColor,
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(20),
                    topRight: Radius.circular(20),
                  ),
                ),
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.1),
                    spreadRadius: 1,
                    blurRadius: 10,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: TabBar(
                controller: _tabController,
                labelColor: AppConstants.PRIMARY_BLUE,
                unselectedLabelColor: Colors.grey[600],
                labelStyle: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
                unselectedLabelStyle: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
                indicator: BoxDecoration(
                  color: AppConstants.PRIMARY_BLUE.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                indicatorSize: TabBarIndicatorSize.tab,
                dividerColor: Colors.transparent,
                padding: const EdgeInsets.all(4),
                tabs: const [
                  Tab(
                    icon: FaIcon(FontAwesomeIcons.coins, size: 18),
                    text: 'Coins',
                  ),
                  Tab(
                    icon: FaIcon(FontAwesomeIcons.crown, size: 18),
                    text: 'VIP Premium',
                  ),
                ],
              ),
            ),
          ),
          SliverFillRemaining(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildCoinsTab(),
                _buildVipTab(),
              ],
            ),
          ),
        ],
      ),
    );
  }
} 